<?php

namespace Book\Controller;

use Book\Model\BookModel;
use Common\Controller\ApiController;
use Common\Model\ModelException;

//use Util\Tree;
//use Util\ModelUtils;
//use Payment\Client\Charge;
//use Util\StringUtils;

class BookController extends ApiController {

    public function search() {
        $input = $this->request();
        $keyword = filter($input['keyword'], '');
        $sex = filter($input['sex'], ''); //适合性别，1为男生2为女生
        $free_time = filter($input['free_time'], ''); //限时免费书本
        $hot = filter($input['hot'], ''); //1为不热门，2为热门
        $eic = filter($input['eic'], ''); //首页今日推荐1为未推荐
        $state = filter($input['state'], ''); //进度0连载1为完结
        $vip = filter($input['vip'], ''); //vip
        $cateId = filter($input['tid'], '');
        $istop = filter($input['is_top'], 1);
        $page = filter($input['page'], 1);
        $perPage = filter($input['per_page'], 10);
        $perPage > 30 && $perPage = 30;
        $orderby = filter($input['orderby'], 'orderby');
        $direction = filter($input['direction'], 'desc');


        $where = [];
        $where['b.closed'] = 0;
        if ($keyword !== '') {
            $keyword = trim($keyword);
            $where['b.title'] = ['like', "%{$keyword}%"];
        }
        if ($sex != '') {
            $where['b.sex'] = $sex;
        }
        if ($free_time != '') {
            $where['b.free_time'] = ['gt', time()];
        }
        if ($hot != '') {
            $where['b.hot'] = $hot;
        }

        if ($eic != '') {
            $where['b.eic'] = $eic;
        }

        if ($cateId !== '') {
            $where['b.tid'] = $cateId;
        }

        if ($state != '') {
            $where['b.state'] = $state;
        }
        if ($state != '') {
            $where['b.vip'] = $vip;
        }

        $count = D('Book')
                ->table('__BOOK__ as b')
                ->scope('valid')->where($where)
                ->cache(2 * 60 * 60)
                ->count();

        $books = M('Book')
                ->table('__BOOK__ as b')
                ->join('__TYPE__ AS t ON t.id = b.tid')
                ->scope('valid')
                ->field('b.*,t.name')
                ->where($where)
                ->cache(2 * 60 * 60)
                ->page($page, $perPage)
                ->order("b.is_top DESC , b.orderby ASC,{$orderby} {$direction}")
                ->select();
        $books = transform('Book', 'listview', $books);
        $pagination = pagination($count, $perPage, $page);
        $this->response($books, $pagination);
    }

    /*
     * 榜单  
     */

    public function views() {
        $input = $this->request();
        $page = filter($input['page'], 1);
        $perPage = filter($input['per_page'], 10);
        $perPage > 30 && $perPage = 30;
        $sex = filter($input['sex'], 1); //适合性别，1为男生2为女生
        $state = filter($input['state'], ''); //进度0连载1为完结
        $vip = filter($input['vip'], ''); //进度0连载1为完结
        $orderby = filter($input['orderby'], 'views'); //addtime
        $direction = filter($input['direction'], 'desc');

        $where = [];
        $where['sex'] = $sex;
        if ($state != '') {
            $where['state'] = $state;
        }
        if ($vip != '') {
            $where['vip'] = $vip;
        }

        $count = D('Book')->scope('valid')->field('id')->where($where)->cache(2 * 60 * 60)->count();
        $books = D('Book')
                ->scope('valid')
                ->field('id,title,views,img,state,author,content')
                ->where($where)
                ->cache(2 * 60 * 60)
                ->order("views DESC ,{$orderby} {$direction}")
                ->page($page, $perPage)
                ->select();

        $books = transform('Book', 'listview', $books);
        $pagination = pagination($count, $perPage, $page);
        $this->response($books, $pagination);
    }

    /*
     * 获取单本书信息
     */

    public function book($id) {
        $input = $this->request();
        $page = filter($input['page'], 1);
        $perPage = filter($input['per_page'], 10);
        $orderby = filter($input['orderby'], 'number');
        $direction = filter($input['direction'], 'ASC');

        $book = D('Book')->scope('valid')->cache(2 * 60 * 60)->find($id);
        $booktype = D('type')->cache(7 * 24 * 60 * 60)->find($book['tid']);
        $book['name'] = $booktype['name'] ? $booktype['name'] : '网络热追';

        //章节
        $BookinfoModel = D('Bookinfo');
        $count = $BookinfoModel->where(['bid' => $book['id'], 'status' => 1])->cache(2 * 60 * 60)->count();
        $book['bookinfo'] = $BookinfoModel
                ->where(['bid' => $book['id'], 'status' => 1])
                ->cache(1 * 24 * 60 * 60)
                ->page($page, $perPage)
                ->order("{$orderby} {$direction}")
                ->select();
        $pagination = pagination($count, $perPage, $page);
        //评论
        $book['comment'] = [];
        $book['comment'] = D('BookComment')->field('content,add_time,user_id')->where(['book_id' => $id, 'is_show' => '1', 'is_top' => 1])->cache(7 * 24 * 60 * 60)->order('is_top desc')->limit(5)->select();
        if (!empty($book['comment'])) {
            //评论者信息
            foreach ($book['comment'] as $key => &$value) {
                $commentUser = D('User')->field('nickname,img,vip')->where(['id' => $value['user_id']])->cache(7 * 24 * 60 * 60)->find();
                $book['comment'][$key] = array_merge($value, $commentUser);
            }
        }

        //是否已经加入书架
        $book['shelves'] = $this->shelves($id);


        $book = transform('Book', 'listview', $book);
        //历史浏览章节
        $book['readhistory'] = [];
        $book['shareurl'] = '';
        if (!empty($this->user)) {
            $uid = $this->user['id'];
            $book['readhistory'] = D('History')->field('number,chapter_id,chapter_page,time')->where(['uid' => $uid, 'biid' => $id])->cache(60)->order('time desc')->find();
            $book['readhistory'] = $book['readhistory'] ? $book['readhistory'] : '';
            $book['shareurl'] = "http://{$_SERVER['SERVER_NAME']}/share.html?id={$uid}";
        }
        $book['buy_chapter_id'] = []; //废弃
        $book['buy_number'] = $this->buyChapterNumber($id);

        $this->response($book, $pagination);
    }

    public function shelves($id) {
        $user = $this->user;
        if ($user['id']) {
            if (D('Bookshelves')->where(['b_id' => $id, 'user_id' => $user['id'], 'del_time' => 0])->find()) {
                $shelves = 1;
            } else {
                $shelves = 0;
            }
        }
        return $shelves;
    }

    /** 获取章节内容* */
    public function chapter() {
        $uid = $this->user['id'];
        $input = $this->request();
        $bid = (int) $input['bid'];
        $is_equal = filter($input['is_equal'], 'eq');
        $chapter_id = (int) filter($input['chapter_id'], 1); //如果没有传章节id则去到第一章
        if (empty($bid)) {
            $this->errorResponse('10001', '参数错误，请退出重进');
        }
        $Bookinfo = D('Bookinfo');
        $where['bid'] = $bid;
        if ($chapter_id != 1) {
            $where['id'] = [$is_equal, $chapter_id];
        } else {
            $is_equal = 'gt';
        }
        $order = $is_equal == 'gt' ? 'id ASC' : 'id DESC';
        $content = $Bookinfo->where($where)->cache(7 * 24 * 60 * 60)->order($order)->find();
        //加入浏览记录
        if ($content && $this->user['id']) {
            $data = [
                'uid' => $this->user['id'],
                'biid' => $content['bid'],
                'number' => $content['title2'],
                'chapter_id' => $chapter_id,
                'time' => time()
            ];
            D('History')->add($data);
        }

        $content = transform('Book', 'content', $content);
        $content['discount_rate'] = C('discount_rate');
        $content['shelves'] = $this->shelves($bid);
        $content['bid'] = $bid;
        $content['buy_number'] = $this->buyChapterNumber($bid);

        $content['nobuynumber'] = [];
        $w['bid'] = $bid;
        $w['status'] = 1;
        if (!empty($content['buy_number'])) {
            $w['number'] = ['not in', $content['buy_number']];
        }
        $content['nobuynumber'] = $Bookinfo->where($w)->cache(7 * 24 * 60 * 60)->getField('number', TRUE);
        $autobuy = D('Autobuy')->field('id')->where(['bid' => $bid, 'uid' => $this->user['id'], 'status' => 1])->count();
        if (!empty($autobuy)) {
            $content['autobuy'] = 1;
        } else {
            $content['autobuy'] = 0;
        }
        //新用户限时免费,后期改用redis
        $redis = redis();
        if ($redis->sismember('freedays', $bid) && empty($redis->exists('freedays_' . $uid . '_' . $bid))) {
            $freedaysModel = D('FreeDays');
            $isfreedays = D('Book')->where(['user_id' => $uid, 'id' => $bid, 'free_days' => ['gt', 0]])->find();
            $time = time();
            $days = $isfreedays['free_days'];
            $id = $freedaysModel->add([
                'bid' => $bid,
                'user_id' => $uid,
                'add_time' => $time,
                'end_time' => strtotime("+{$days}day"),
            ]);
            $redis->set('freedays_' . $uid . '_' . $bid, strtotime("+{$days}day"));
        }
        $this->response($content);
    }

    /** 提交书评* */
    public function comment($id) {
        $user = $this->user;
        $input = $this->request();
        $content = filter($input['content'], '');
        if (empty($content) || strlen($content) < 5) {
            $this->errorResponse(90001, '评论内容必须大于5个字符', 400);
        }
        $data = [
            'book_id' => $id,
            'user_id' => $user['id'],
            'content' => $content,
            'add_time' => time()
        ];
        $BookComment = D('BookComment');
        $BookComment->create($data);
        if ($BookComment->add()) {
            $data = ['success' => true, 'message' => '发表成功,后台即将审核'];
            /* 每日任务 */
            $uid = $user['id'];
            D('Task/task')->taskOnceRedis($uid, 'task_once' . $uid, 13); //13代表的任务id 13
            /* 每日任务 */
            $this->createdResponse($data);
        }
    }

    /** 加入书架* */
    public function addshelves($id) {
        $user = $this->user;
        $uid = $user['id'];
        $input = $this->request();
        D('Bookshelves')->create(['b_id' => $id, 'user_id' => $uid, 'add_time' => time()]);
        if (D('Bookshelves')->add()) {//新人任务
            $userinfo = $this->userinfo;
            if ($userinfo['vip'] > 0)D('Task/task')->taskOnceRedis($uid, 'task_once' . $uid, 2); //2对应是任务id
        }
        $this->createdResponse();//无论失败成功都正确返回
    }

    /** 书架列表* */
    public function bookshelves() {
        $input = $this->request();
        $page = filter($input['page'], 1);
        $perPage = filter($input['per_page'], 10);
        $user = $this->user;
        $users[] = $user['id'];
        if (!empty($input['temp_uid'])) {
            $users[] = $input['temp_uid'];
        }
        $BookshelvesModel = D('Bookshelves');
        $count = $BookshelvesModel->where(['user_id' => ['in', $users], 'del_time' => 0])->count();
        $Bookshelves = [];
        if (!empty($count)) {
            $Bookshelves = $BookshelvesModel
                    ->table('__BOOKSHELVES__ as s')
                    ->join('__BOOK__ as b on s.b_id = b.id ')
                    ->field('b.id,b.title,b.img,b.state')
                    ->where(['s.user_id' => ['in', $users], 's.del_time' => 0])
                    ->group('b.id')
                    ->page($page, $perPage)
                    ->order('s.add_time desc')
                    ->select();
            foreach ($Bookshelves as $k => $v) {
                $bookinfo = D('Bookinfo')->field('id,bid,title2')->where(['bid' => $v['id']])->cache(7 * 24 * 60 * 60)->select();
                $arrLen = count($bookinfo);
                $Bookshelves[$k]['end_chapter'] = $bookinfo[$arrLen - 1]['title2'];

                $history = D('History')->field('number,chapter_id')->where(['biid' => $v['id'], 'uid' => $user['id']])->order('id desc')->find();
                $Bookshelves[$k]['history'] = $history['number'] ? $history['number'] : '';
                $Bookshelves[$k]['h_chapter_id'] = $history['chapter_id'] ? $history['chapter_id'] : 0;

                if ($history['chapter_id']) {
                    $arrids = array_column($bookinfo, 'id');
                    $curkey = array_search($history['chapter_id'], $arrids);
                    $Bookshelves[$k]['advance'] = 100 * round($curkey / $arrLen, 2);
                } else {
                    $Bookshelves[$k]['advance'] = 0;
                }
            }
        }

        $pagination = pagination($count, $perPage, $page);
        $this->response($Bookshelves, $pagination);
    }

    /*     * 删除书架* */

    public function delshelves() {
        $input = $this->request();
        $idArr = explode(',', $input['ids']);
        $uid = $this->user['id'];
        $users[] = $uid;
        if (!empty($input['temp_uid'])) {
            $users[] = $input['temp_uid'];
        }
        if (count($idArr) > 0) {
            D('Bookshelves')->where(['user_id' => ['in', $users], 'b_id' => ['in', $idArr]])->setField(['del_time' => time()]);
        }
        $this->createdResponse();
    }

    /*     * 搜索词* */

    public function keyword() {
        $leywords = D('Keywords')
                ->table('__KEYWORDS__ AS k')
                ->join('__BOOK__ AS b ON k.bid =b.id')
                ->field('k.bid,k.biid,k.keyword')
                ->where(['b.closed' => 0])
                ->cache(1 * 24 * 60 * 60)
                ->limit('10')
                ->order('k.clicknum DESC')
                ->select();
        $this->response($leywords);
    }

    /*     * 购买章节* */

    public function buyChapter() {
        $user = $this->userinfo;
        $uid = $user['id'];
        $input = $this->request();
        $bid = (int) $input['bid'];
        $numbers = $input['numbers']; //购买的章节'1,2,3,4,20,33'
        $cost_gold = $input['cost_gold'];
        if ($user['gold'] < $cost_gold) {
            $this->errorResponse('10001', '书币不够，请充值');
        }
        try {
            $ChapterBuyModel = D('ChapterBuy');
            $ChapterBuyModel->startTrans();
            $where = [
                'user_id' => $user['id'],
                'bid' => $bid,
            ];
            $result = $ChapterBuyModel->where($where)->find();
            if ($result) {
                $data['id'] = $result['id'];
                $data['number'] = $result['number'] . ',' . $numbers;
                $data['add_time'] = time();
                $res1 = $ChapterBuyModel->where($where)->setField($data);
            } else {
                $res1 = $ChapterBuyModel->add([
                    'bid' => $bid,
                    'number' => $numbers,
                    'user_id' => $user['id'],
                    'add_time' => time()
                ]);
            }
            $res2 = D('User')->where(['id' => $user['id']])->setDec('gold', $cost_gold);
            $res3 = D('Account/GoldLog')->addGoldLog(['user_id' => $user['id'], 'mark' => '购买书籍花费', 'gold' => $cost_gold, 'type' => 'cost', 'bid' => $bid, 'add_time' => time()]);
            if (!empty($res1) && !empty($res2) && !empty($res3)) {
                $ChapterBuyModel->commit();
            } else {
                $ChapterBuyModel->rollback();
                $this->errorResponse('10001', '购买失败，请重试');
            }
        } catch (ModelException $e) {
            $this->errorModelResponse($e);
        }
        $uid = $user['id'];
        /* 每日任务 */
        D('Task/task')->taskOnceRedis($uid, 'task_once' . $uid, 3); //3代表的任务id 3
        /* 每日任务 */
        $gold = D('User')->where(['id' => $user['id']])->getField('gold');
        $this->createdResponse(['message' => '购买成功', 'code' => '200', 'gold' => $gold]);
    }

    public function buyChapterNumber($bid) {
        $user = $this->user;
        $ChapterBuy = D('ChapterBuy')->where(['user_id' => $user['id'], 'bid' => $bid])->find();
        if (!empty($ChapterBuy)) {
            $numbers = explode(',', $ChapterBuy['number']);
        } else {
            $numbers = [];
        }
        return $numbers;
    }

    public function getAllChapter($id) {
        $input = $this->request();
        $page = filter($input['page'], 1);
        $BookinfoModel = D('Bookinfo');
        $count = $BookinfoModel->where(['bid' => $id, 'status' => 1])->count();
        $perPage = filter($input['per_page'], $count);
        $chaptes = $BookinfoModel
                ->field('id,title2,gold,time,number')
                ->where(['bid' => $id, 'status' => 1])
                ->page($page, $perPage)
                ->select();
        $pagination = pagination($count, $perPage, $page);
        $this->response($chaptes, $pagination);
    }

    /**
     * 
     * @param type $id所有章节
     */
    public function getAllChapter2($id) {
        $input = $this->request();
        $page = filter($input['page'], 1);
        $perPage = filter($input['per_page'], 10);
        $orderby = filter($input['orderby'], 'number');
        $direction = filter($input['direction'], 'ASC');
        $uid = $this->user['id'];

        //查询用户限免是否过期
        $time = time();
        $freedays = D('FreeDays')->where(['user_id' => $uid, 'bid' => $id])->find();
        if (!empty($freedays)) {
            if ($freedays['end_time'] < time()) {
                $chaptes['isfreetime'] = 0; //限时免费已结束
            } else {
                $chaptes['isfreetime'] = 1;
            }
        } else {
            $book = D('Book')->where(['id' => $id, 'free_days' => ['gt', 0]])->find();
            if (!empty($book)) {
                $chaptes['isfreetime'] = 1;
            } else {
                $chaptes['isfreetime'] = 0;
            }
        }
        $BookinfoModel = D('Bookinfo');
        $count = $BookinfoModel->where(['bid' => $id, 'status' => 1])->cache(7 * 24 * 60 * 60)->order("{$orderby} {$direction}")->count();
        $chaptes['chapters'] = [];
        if ($count > 0) {
            $perPage = filter($input['per_page'], $count);
            $chaptes['chapters'] = $BookinfoModel
                    ->field('id,title2,gold,time,number')
                    ->where(['bid' => $id, 'status' => 1])
                    ->cache(7 * 24 * 60 * 60)
                    ->order("{$orderby} {$direction}")
                    ->page($page, $perPage)
                    ->select();
        }

        $pagination = pagination($count, $perPage, $page);
        $chaptes['buy_number'] = $this->buyChapterNumber($id);
        $book = D('Book')->field('title')->cache(7 * 24 * 60 * 60)->find($id);
        $chaptes['title'] = $book['title']; //新增20190319
        //配合ios隐藏支付审查制
        if (!empty($this->v_ios)) {
            $v_ios = C('V_IOS');
            $curr_ios = intval($this->v_ios);
            if ($curr_ios == $v_ios) {
                $chaptes['isfreetime'] = 1; //1是章节免费
            }
        }
        $this->response($chaptes, $pagination);
    }

    /*
     * 自动购买和取消自动购买，同一个接口
     */

    public function autobuy() {
        $input = $this->request();
        if (empty($input['bid'])) {
            $this->errorResponse('10001', '书本ID不在');
        }
        $status = $input['status'];
        $bid = $input['bid'];
        $uid = $this->user['id'];

        $data = [
            'bid' => $bid,
            'uid' => $uid,
            'status' => $status,
            'add_time' => time()
        ];
        $autobuyModel = D('Autobuy');
        $where['bid'] = $bid;
        $where['uid'] = $uid;
        $result = $autobuyModel->where($where)->save($data);
        if (empty($result)) {
            $result = $autobuyModel->add($data);
        }
        $this->createdResponse();
    }

    public function getAutobuy() {
        $input = $this->request();
        $page = filter($input['page'], 1);
        $perPage = filter($input['per_page'], 10);

        $orderby = filter($input['orderby'], 'add_time');
        $direction = filter($input['direction'], 'DESC');

        $where['a.status'] = 1;
        $where['a.uid'] = $this->user['id'];
        $autobuy = D('Autobuy');
        $count = $autobuy->table("__AUTOBUY__ AS a")->where($where)->count();
        if ($count > 0) {
            if (!empty($input['bid'])) {
                $where['b.id'] = $input['bid'];
            }
            $auto = $autobuy->table("__AUTOBUY__ AS a")
                    ->join('__BOOK__ AS b on b.id = a.bid')
                    ->field('b.title,b.id,b.img,b.author,b.content,a.add_time')
                    ->where($where)
                    ->page($page, $perPage)
                    ->select();
        }


        $pagination = pagination($count, $perPage, $page);
        $this->response($auto, $pagination);
    }

    /*     * 新用户免费* */

    /*     * 新人限免* */

    public function newsfreeDays() {
        $input = $this->request();
        $page = filter($input['page'], 1);
        $perPage = filter($input['per_page'], 10);
        $orderby = filter($input['orderby'], 'add_time');
        $direction = filter($input['direction'], 'DESC');
        $istop = filter($input['is_top'], 1);
        $hot = filter($input['hot'], ''); //1为不热门，2为热门
        $sex = filter($input['sex'], ''); //适合性别，1为男生2为女生

        $w = ' ';
        if ($sex != '') {
            $w = " b.sex = $sex  and ";
        }

        if ($hot != '') {
            $w = " b.hot = {$hot} and  ";
        }


        $BookModel = D('Book');

        $uid = $this->user['id'];

        if ($page == 1) {
            $start = 0;
        } else {
            $start = $page * $perPage;
        }
        $endpage = $page * $perPage;
        $Model = M();
        $time = time();
        $count_sql = "SELECT count(*) as num FROM `n_book` AS b WHERE {$w} `closed` = 0 AND `del_time` = 0 AND `free_days` > 0 AND NOT EXISTS (SELECT id FROM n_free_days AS f WHERE f.user_id = {$uid} AND f.bid = b.id and f.end_time <{$time})";
        $data_sql = "SELECT b.id,b.free_days,b.img,b.title,b.content,b.state,b.author,t.name FROM `n_book` AS b left join n_type as t on t.id = b.tid  WHERE {$w}  b.closed = 0 AND b.del_time = 0 AND b.free_days > 0 AND NOT EXISTS (SELECT f.end_time FROM n_free_days AS f WHERE f.user_id = {$uid} AND f.bid = b.id AND f.end_time< {$time} ) order by {$orderby} {$direction} limit {$start},{$endpage}";
        $count = M()->query($count_sql);
        $freebook = M()->query($data_sql);
        foreach ($freebook as $k => &$v) {
            $redisKey = 'freedays_' . $uid . '_' . $v['id'];
            $redis = redis();
            if ($redis->exists($redisKey)) {
                $freebook[$k]['end_time'] = $redis->get($redisKey);
            } else {
                $freebook[$k]['end_time'] = strtotime("+{$v['free_days']}day");
            }
        }
        $count = $count[0]['num'];
        $books = transform('Book', 'freedays', $freebook);
        $pagination = pagination($count, $perPage, $page);
        $this->response($freebook, $pagination);
    }

    /*
     * 引导页推荐下载打开APP首次请求接口，返回至引导页续看
     */

    public function firstOpen() {
        $ip = get_client_ip();
        $adModel = D('AdPage');
        $where['click_ip'] = $ip;
        $where['status'] = 0;
        $adpage = $adModel->field('bid,number,chapter_id')->where($where)->order('id desc')->find();
        if (!empty($adpage)) {
            $adpage['status'] = 1;
            $adModel->setField($adpage);
            $uid = $this->user['id'];
            $bookshelves = D('Bookshelves')->where(['user_id' => $uid, 'b_id' => $adpage['bid'], 'del_time' => 0])->find();
            $adpage['shelves'] = 0;
            if (!empty($bookshelves)) {
                $adpage['shelves'] = 1;
            }
        } else {
            $adpage['data'] = null;
        }


        $this->response($adpage);
    }

}
